"""
比对两个红外传感器的灵敏度。
"""

from machine import Pin
import time

sr602_pin = Pin(0, Pin.IN, Pin.PULL_DOWN)
sr501_pin = Pin(1, Pin.IN, Pin.PULL_DOWN)

records = []
rounds = 0

while True:
    print('Waiting for SR602 and SR501 to recover...')
    while True:
        if sr602_pin.value() == 0 and sr501_pin.value() == 0:
            break
    print('All Recovered')

    print("\033[92m\n\n\nTry trigger them now --------------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>\033[0m")

    record = [None, None]
    while True:
        if record[0] is None and sr602_pin.value() == 1:
            timestamp = time.ticks_ms() / 1000
            record[0] = timestamp
            print("\033[93mSR602 @[{:.3f}]\033[0m".format(timestamp))

        if record[1] is None and sr501_pin.value() == 1:
            timestamp = time.ticks_ms() / 1000
            record[1] = timestamp
            print("\033[94mSR501 @[{:.3f}]\033[0m".format(timestamp))

        if record[0] is not None and record[1] is not None:
            records.append(record)
            print(f'Done! Delta: {(record[0] - record[1]):.3f} s')
            break
        elif record[0] is not None and record[1] is None:
            if time.ticks_ms() / 1000 - record[0] > 3:
                records.append(record)
                print('Timeout!')
                break
        elif record[0] is None and record[1] is not None:
            if time.ticks_ms() / 1000 - record[1] > 3:
                records.append(record)
                print('Timeout!')
                break

    rounds += 1
    if rounds >= 20:
        break

print('\nSummary:')
for record in records:
    if record[0] is not None and record[1] is not None:
        delta_ms = record[0] - record[1]
        print(f"SR602 @[{record[0]:.3f}], SR501 @[{record[1]:.3f}], Delta: {delta_ms:.3f} s")
    else:
        str = ''

        if record[0] is None:
            str = f"SR602 @[N/A], "
        else:
            str = f"SR602 @[{record[0]:.3f}], "
            
        if record[1] is None:
            str += f"SR501 @[N/A]"
        else:
            str += f"SR501 @[{record[1]:.3f}]"

        print(str)